import { tokenLogin } from "@/apis/account"
import { getToken, removeToken, setToken, setSn, removeSn, setUser, setUid } from "./auth"
import { useUserStore } from "@/store";

let subscribes: (() => void)[] = []
let flag = false // 设置开关，保证一次只能请求一次短token，防止多此操作，多次请求

/*把过期请求添加在数组中*/
export const addRequest = (request: () => void) => {
  subscribes.push(request)
}

/*调用过期请求*/
export const retryRequest = () => {
  console.log('重新请求上次中断的数据');
  subscribes.forEach(request => request())
  subscribes = []
}

/*短token过期，携带token去重新请求token*/
export const refreshToken = () => {
  if (!flag) {
    flag = true;
    let r_tk = getToken() // 获取长token
    if (r_tk) {
      tokenLogin({ token: r_tk }).then((res) => {
        console.log(res);

        //长token失效，退出登录
        if (res.code === -997) {
          flag = false
          removeSn()
          removeToken()
          uni.showToast({
            title: '登录过期，请重新登录',
            icon: 'none',
            duration: 1500,
            complete: () => {
              // 跳转到登录页面
              const pages = getCurrentPages()
              const currentPage = pages[pages.length - 1];
              if (currentPage.route !== 'pages/login/login') {
                uni.navigateTo({
                  url: '/pages/login/login'
                })
              }
            }
          })
        } else if (res.ok === 1) {
          // 存储新的token
          console.log(res.data);
          setUserData(res.data)
          setToken(res.data.token)
          setSn(res.data.sn)
          flag = false
          // 重新请求数据
          retryRequest()
        }
      })
    }
  }
}

const setUserData = (data: any) => {
  const userStore = useUserStore()
  const { sn, token } = data
  userStore.setUserInfo(data)
  userStore.setToken(token)
  userStore.setSn(sn)
  setSn(sn)
  setToken(token)
  setUser(data)
  setUid(data.uid)
}